//
//  ReciteViewController.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/10/11.
//
//  成语和规范词背诵界面

import UIKit
import CoreData
import AVFAudio
import SVProgressHUD
import EmptyPage

private let kReciteTitleCell = "ReciteTitleCell"
private let kReciteItemCell = "ReciteItemCell"
private let kWebSearchCell = "WebSearchCell"

enum ReciteMode: String {
    /// 随机模式
    case random = "随机"
    /// 权重模式
    case weight = "权重"
}

class ReciteViewController: BaseViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var nextBtn: UIButton!
    @IBOutlet weak var gotItBtn: UIButton!
    @IBOutlet weak var doNotUnderstandBtn: UIButton!
    
    var type: PracticeType = .reciteIdiom
    var model: ReciteViewModel!
    
    private var barBtn: UIBarButtonItem!
    private var mode: ReciteMode = .weight
    private var datas = [BaseCellModel]()
    private var seconds: Int = 0
    
    /// 是否显示解释
    private var showExplain: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupTableView()
        addGesture()
        loadDatas()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        setupTimer(count: model.count)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        var statiType: TimeStatisticsType = .reciteIdiom
        if type == .reciteSpecification {
            statiType = .reciteSpecification
        }
        
        TimeStatisticsStore.record(uuid: uuid, duration: TimeInterval(seconds), type: statiType)
    }
    
    override func timing() {
        super.timing()
        
        seconds = seconds + 1
    }
    
    // 不会，权重加1
    @IBAction func doNotUnderstand(_ sender: Any) {
        guard let keyword = model.keyword else { return }
 
        changeWeight(keyword: keyword, weight: 1, oper: .add)
        next2()
    }
    
    // 会了，权重减1
    @IBAction func gotIt(_ sender: Any) {
        gotIt2()
    }
    
    // 下一个
    @IBAction func next(_ sender: Any) {
        next2()
    }
    
    // MARK: - private
    
    private func setupTableView() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: kReciteTitleCell , bundle: nil), forCellReuseIdentifier: kReciteTitleCell)
        tableView.register(UINib(nibName: kReciteItemCell , bundle: nil), forCellReuseIdentifier: kReciteItemCell)
        tableView.register(UINib(nibName: kWebSearchCell , bundle: nil), forCellReuseIdentifier: kWebSearchCell)
        
        tableView.emptyView(imageName:"com_tableview_null" ,text: "你还没有导入数据，请先导入数据后再试试。", btnTitle: "如何导入数据？") {
            FuncationListViewController().push()
        }
        
        let modeStr = UserDefaults.standard.string(forKey: kUserDefaults_ReciteMode) ?? ReciteMode.random.rawValue
        mode = ReciteMode(rawValue: modeStr) ?? .random
        
        barBtn = UIBarButtonItem(title: "随机", style: .plain, target: self, action: #selector(changeMode(item:)))
        navigationItem.rightBarButtonItem = barBtn
        barBtn.title = mode.rawValue
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.loadDatas), name: .refreshReciteViewController, object: nil)
    }
    
    @objc private func loadDatas() {
        model = ReciteViewModel(type: type)
        setupTimer(count: model.count)
        next2()
    }
    
    @objc private func gotIt2() {
        guard let keyword = model.keyword else { return }
        
        changeWeight(keyword: keyword, weight: 1, oper: .subtract)
        SVProgressHUD.showSuccess(withStatus: "我会了")
        next2()
    }
    
    private func addGesture() {
        // 单击，显示解释/答案
        let tap = UITapGestureRecognizer(target: self, action: #selector(self.showExplain2))
        tap.numberOfTapsRequired = 1
        tableView.addGestureRecognizer(tap)
        
        // 双击，我会了
        let tap2 = UITapGestureRecognizer(target: self, action: #selector(self.gotIt2))
        tap2.numberOfTapsRequired = 2
        tableView.addGestureRecognizer(tap2)
        tap.require(toFail: tap2)
        
        // 滑动手势
        let pan = UIPanGestureRecognizer()
        pan.delegate = self
        tableView.addGestureRecognizer(pan)
    }
    
    // 显示解释
    @objc private func showExplain2() {
        showExplain = true
        tableView.reloadData()
    }
    
    @objc private func changeMode(item: UIBarButtonItem) {
        if mode == .random {
            mode = .weight
        } else {
            mode = .random
        }
        barBtn.title = mode.rawValue
        model.changeMode(mode: mode)
        
        SVProgressHUD.showSuccess(withStatus: "已切换至\(mode.rawValue)模式")
        next2()
    }
    
    // 下一个
    private func next2() {
        showExplain = false
        
        if let data = model.next() {
            datas = data
            tableView.reloadData()
            nextBtn.isHidden = false
            gotItBtn.isHidden = false
            doNotUnderstandBtn.isHidden = false
        } else {
            nextBtn.isHidden = true
            gotItBtn.isHidden = true
            doNotUnderstandBtn.isHidden = true
        }
    }
    
    // 上一个
    private func previous() {
        if let data = model.previous() {
            datas = data
            tableView.reloadData()
        }
    }
    
    private func changeWeight(keyword: String, weight: Int, oper: WeightOper) {
        if type == .reciteIdiom {
            IdiomStore.changeWeight(title: keyword, weight: 1, oper: oper)
        } else if type == .reciteSpecification || type == .reciteIssuesAndMeasure {
            SpecificationStore.changeWeight(title: keyword, weight: 1, oper: oper)
        }
    }
}

// 手势返回
extension ReciteViewController: UIGestureRecognizerDelegate {
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        let pan = gestureRecognizer as? UIPanGestureRecognizer
        if let point = pan?.velocity(in: pan?.view) {
            // y值大于80则认为是上下滚动
            if abs(point.y) > 100 { return false }
            if point.x < 0 { // 左滑
                next2()
                return true
            } else if point.x > 0 { // 右滑
                previous()
                return true
            }
        }
        
        return false
    }
}

extension ReciteViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if datas.count == 0 { return 0 }
        return showExplain ? datas.count : 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = datas[indexPath.row]
        if model is TitleCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: kReciteTitleCell, for: indexPath) as! ReciteTitleCell
            let m = model as! TitleCellModel
            cell.titleLabel.text = m.title
            return cell
        } else if model is ItemCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: kReciteItemCell, for: indexPath) as! ReciteItemCell
            let m = model as! ItemCellModel
            cell.titleLabel.text = m.title
            cell.contentLabel.text = m.content
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: kWebSearchCell, for: indexPath) as! WebSearchCell
            let m = model as! WebSearchCellModel
            cell.model = m
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}
